#include <iostream>
#include <signal.h>
#include "oj_control.hpp"
#include "../comm/httplib.h"

using namespace httplib;
using namespace ns_control;

static Control *ctrl_ptr = nullptr;

void Recovery(int signo)
{
    // 收到信号后，上线所有主机
    ctrl_ptr->RecoveryMachine();
}

int main()
{
    signal(SIGQUIT, Recovery); // 处理信号

    Server svr;

    Control ctrl;
    ctrl_ptr = &ctrl;

    // 获取题库所有题目的信息
    // 当访问 /all_questions 路径时，调用回调函数
    svr.Get("/all_questions", [&ctrl](const Request &req, Response &resp)
            {
                std::string html;
                ctrl.AllQuestions(&html);
                resp.set_content(html, "text/html;charset=utf-8"); });

    // 获取指定题目的信息
    svr.Get(R"(/question/(\d+))", [&ctrl](const Request &req, Response &resp)
            {
        std::string number=req.matches[1];//获取题目序号
        std::string html;
        ctrl.OneQuestion(number,&html);

        resp.set_content(html,"text/html;charset=utf-8"); });

    // 编译并运行用户提交的代码
    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp)
             {
        std::string number=req.matches[1];//获取题目序号
        std::string result_json;
        
        ctrl.Judge(number,req.body,&result_json);

        resp.set_content(result_json,"application/json;charset=utf-8"); });

    svr.set_base_dir("./wwwroot"); // 所有静态文件将从这个目录获取服务
    svr.listen("0.0.0.0", 8080);   // 监听的IP和端口

    return 0;
}